package cc.ufinity.networkdiagnose.manager;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.util.HttpUtils;
import cc.ufinity.networkdiagnose.view.R;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public final class DBManager {
	private Activity ctx;

	private static final String CREATE_FTP = "create table ftp (_id integer primary key autoincrement, address text not null, "
			+ "port integer not null, username text not null, password text not null);";
	private static final String CREATE_TASK = "create table task (_id integer primary key autoincrement, "
			+ "address text not null,apname text not null,taskid text not null);";
	private static final String CREATE_ACCOUNT = "create table account (_id integer primary key autoincrement, "
			+ "username text not null, password text, autologin integer);";
	//这个表存储的中国电信的帐号信息
	private static final String CREATE_CHINANET_ACCOUNT = "create table chinaaccount (_id integer primary key autoincrement, "
			+ "username text not null, password text,address text, autologin integer);";
	//这个这个表存储的中国电信的帐号信息
	private static final String CREATE_UNICOM_ACCOUNT = "create table unicomaccount (_id integer primary key autoincrement, "
			+ "username text not null, password text,address text, autologin integer);";
	
	private static final String CREATE_WEBAUTH = "create table webauth (_id integer primary key autoincrement, "
			+ "username text not null, password text, wlanacip text, wlanacname text, wlanuserip text ,logonsessid text);";
	private static final String CREATE_Version = "create table version (_id integer primary key autoincrement, "
			+ "version text not null, downloadurl text, description text);";
	
	private static final String CREATE_CHINANET_LogoutParamStr = "create table logoutParamStr (_id integer primary key autoincrement, ip text not null, "
		+ "realIp text not null, paramStr text not null);";
	
	 
	private static final String DATABASE_NAME = "NetworkTest.db";
	private static final int DATABASE_VERSION = 1;
	private static DBManager dbManager = null;
	private SQLiteDatabase mDb;
	private FTPConfigParser parser;
	private FTPConfig config ;
	private static final String TEST_ADDRESS= "create table address (_id integer primary key autoincrement, "
		+ "city text not null, town text);";
	class DbHelper extends SQLiteOpenHelper {

		public DbHelper(Activity context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			/*db.execSQL(CREATE_FTP);
			db.execSQL(CREATE_CHINANET_ACCOUNT);
			db.execSQL(CREATE_UNICOM_ACCOUNT);
			db.execSQL(CREATE_CHINANET_LogoutParamStr);
			db.execSQL(CREATE_TASK);
			db.execSQL(CREATE_ACCOUNT); 
			db.execSQL(CREATE_WEBAUTH);
			db.execSQL(TEST_ADDRESS);
			System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   创建数据库");
			db.execSQL(CREATE_Version);*/
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			/*db.execSQL("DROP TABLE IF EXISTS ftp");
			db.execSQL("DROP TABLE IF EXISTS task");
			db.execSQL("DROP TABLE IF EXISTS account");
			db.execSQL("DROP TABLE IF EXISTS chinaaccount");
			db.execSQL("DROP TABLE IF EXISTS unicomaccount");
			db.execSQL("DROP TABLE IF EXISTS webauth");
			db.execSQL("DROP TABLE IF EXISTS version");
			db.execSQL("DROP TABLE IF EXISTS address");
			db.execSQL("DROP TABLE IF EXISTS logoutParamStr");*/
			onCreate(db);
		}		
	}

	public DBManager(Activity ctx) {
		this.ctx = ctx;
		DbHelper help = new DbHelper(ctx);
		mDb = help.getWritableDatabase();
		
		try {
			mDb.execSQL(CREATE_FTP);
		} catch(Exception e) {}
		
		try {
			mDb.execSQL(CREATE_CHINANET_ACCOUNT);
		} catch(Exception e) {}
		try {
			mDb.execSQL(CREATE_UNICOM_ACCOUNT);
		} catch(Exception e) {}
		try {
			mDb.execSQL(CREATE_CHINANET_LogoutParamStr);
		} catch(Exception e) {}
		try {
			mDb.execSQL(CREATE_ACCOUNT); 
		} catch(Exception e) {}
		try {
			mDb.execSQL(CREATE_TASK);
		} catch(Exception e) {}
		try {
			mDb.execSQL(CREATE_WEBAUTH);
		} catch(Exception e) {}
		try {
			mDb.execSQL(TEST_ADDRESS);
		} catch(Exception e) {}
	}
	
	 public void getConfig(DBManager db){
		 config = new FTPConfig();
		 parser = new FTPConfigParser();
		 String url = "http://120.209.198.188:8084/Task/ConfigXml.aspx";
		 InputStream is;
		try {
			is = HttpUtils.getInputStream(url);
			 config = parser.parseFtpInfo(is);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}   
		if(config !=null){
			System.out.println(config.address+":"+config.userName+":"+config.port+":"+config.password+"=============================ftpconfig");
			db.saveFtp(config);
		}
		db.release();
	 }
	@Deprecated
	public static DBManager getInstance(Activity ctx) {
		if (null == dbManager) {
			dbManager = new DBManager(ctx);
		}

		return dbManager;
	}

	public void release() {
		mDb.close();
	}
	
	/**
	 * 获取的是环境信息的数目
	 * @return
	 */
	public MessageNum getMessageNum(){
		MessageNum Num=null;
		Cursor mCursor = mDb.query("refresh", null, null, null, null, null, null);
		if (mCursor.moveToFirst()) {
			Num = new MessageNum();
			Num.num=mCursor.getInt(0)+"" ;
		}
		mCursor.close();
		return Num; 
	}
	
	/**
	 * 保存环境测试的数目
	 * @param Num
	 * @return
	 */
	public boolean saveMessageNum(MessageNum Num){
		ContentValues values = new ContentValues();
		values.put("num", Num.num);
		
		MessageNum temp = getMessageNum();
		if (null == temp) {
			return (mDb.insert("refresh", null, values)) > 0;
		} else {
			return (mDb.update("refresh", values, "_id=?", new String[] { ""
					+ temp.num})) > 0;
		}
	}
	
	public FTPConfig getFtp() {
		if (!mDb.isOpen()) {
			System.out.println("mdb is nulllllllllllllllll");
		}
		FTPConfig ftp = null;
		Cursor mCursor = mDb.query("ftp", null, null, null, null, null, null);
		if (mCursor.moveToFirst()) {
			ftp = new FTPConfig();
			ftp.id = mCursor.getInt(0);
			ftp.address = mCursor.getString(1);
			ftp.port = mCursor.getInt(2);
			ftp.userName = mCursor.getString(3);
			ftp.password = mCursor.getString(4);
		}
		mCursor.close();
		return ftp; 
	}
	 
	//从服务端获取ftp账号信息
	public FTPConfig getFtp2() {
		return getFtp();
	}

	public int deleteFtp() {
		return mDb.delete("ftp", null, null);
	}

	public boolean saveFtp(FTPConfig ftp) {
		ContentValues values = new ContentValues();
		values.put("address", ftp.address);
		values.put("port", ftp.port);
		values.put("username", ftp.userName);
		values.put("password", ftp.password);
		FTPConfig temp = getFtp();
		if (null == temp) {
			return (mDb.insert("ftp", null, values)) > 0;
		} else {
			return (mDb.update("ftp", values, "_id=?", new String[] { ""
					+ temp.id })) > 0;
		}
	}

	public List<TaskConfig> getTask(String apname, String taskid) {
		List<TaskConfig> tasks = new ArrayList<TaskConfig>();
		TaskConfig task = null;
		String where = "apname=? and taskid=?";
		String whereArg[] = new String[] { apname, taskid };
		Cursor mCursor = mDb.query("task", null, where, whereArg, null, null,
				null);
		while (mCursor.moveToNext()) {
			task = new TaskConfig();
			task.id = mCursor.getInt(0);
			task.address = mCursor.getString(1);
			tasks.add(task);
		}
		return tasks;
	}

	public List<TaskConfig> getTask() {
		List<TaskConfig> tasks = new ArrayList<TaskConfig>();
		TaskConfig task = null;
		Cursor mCursor = mDb.query("task", null, null, null, null, null, null);
		while (mCursor.moveToNext()) {
			task = new TaskConfig();
			task.id = mCursor.getInt(0);
			task.address = mCursor.getString(1);
			task.apname = mCursor.getString(2);
			task.taskid = mCursor.getString(3);
			tasks.add(task);
		}
		mCursor.close();
		return tasks;
	}

	public boolean taskFinished(List<TaskConfig> tasks, String address,
			String taskid) {
		Iterator<TaskConfig> it = tasks.iterator();
		TaskConfig task = null;
		boolean exist = false;
		while (it.hasNext()) {
			task = it.next();
			String addr = task.address;
			String id = String.valueOf(task.taskid);
			if (addr.equalsIgnoreCase(address) && id.equalsIgnoreCase(taskid)) {
				exist = true;
				break;
			}
		}
		return exist;
	}

	public void saveTask(String address, String apname, String taskid) {
		List<TaskConfig> tasks = getTask();
		Iterator<TaskConfig> it = tasks.iterator();
		TaskConfig task = null;
		boolean exist = false;
		while (it.hasNext()) {
			task = it.next();
			if (task.address.equalsIgnoreCase(address)
					&& String.valueOf(task.id).equalsIgnoreCase(taskid)) {
				exist = true;
				break;
			}
		}
		if (!exist) {
			ContentValues values = new ContentValues();
			values.put("address", address);
			values.put("apname", apname);
			values.put("taskid", taskid);
			mDb.insert("task", null, values);
			// mDb.update("task", values, "_id=?", new String[] { "" + temp.id
			// });
		}
	}

	/**
	 * 这个是为了获取代表中国移动的帐号信息
	 * @return
	 */
	public Account getAccount() {
		Account account = null;
		try{
			Cursor mCursor = mDb.query("account", null, null, null, null, null,null);
			if (mCursor.moveToFirst()) {
				account = new Account();
				account.id = mCursor.getInt(0);
				account.userName = mCursor.getString(1);
				account.password = mCursor.getString(2);
				Log.e("account", "" + account.password);
				account.autoLogin = mCursor.getInt(3);
			}
			mCursor.close();
		}catch(Exception e){
			e.printStackTrace();
		} 
		return account;
	}
	/**
	 * 这个方法是获取代表中国电信的账号信息
	 * @return
	 */
	public ChinaNetAccount getChinaNetAccount() {
		ChinaNetAccount account = null;
		try{
			Cursor mCursor = mDb.query("chinaaccount", null, null, null, null, null,null);
			if (mCursor.moveToFirst()) {
				account = new ChinaNetAccount();
				account.id = mCursor.getInt(0);
				account.userName = mCursor.getString(1);
				account.password = mCursor.getString(2);
				account.address=mCursor.getString(3);
				Log.e("chinaaccount", "" + account.password);
				account.autoLogin = mCursor.getInt(4);
			}
			mCursor.close();
		}catch(Exception e){
			account = null;
			e.printStackTrace();
		} 
		return account;
	}
	
	/**
	 * 这个方法是获取代表中国联通的账号信息
	 * @return
	 */
	public ChinaUnicomAccount getUnicomAccount() {
		ChinaUnicomAccount account = null;
		try{
			Cursor mCursor = mDb.query("unicomaccount", null, null, null, null, null,null);
			if (mCursor.moveToFirst()) {
				account = new ChinaUnicomAccount();
				account.id = mCursor.getInt(0);
				account.userName = mCursor.getString(1);
				account.password = mCursor.getString(2);
				account.address=mCursor.getString(3);
				Log.e("unicomaccount", "" + account.password);
				account.autoLogin = mCursor.getInt(4);
			}
			mCursor.close();
		}catch(Exception e){
			account = null;
			e.printStackTrace();
		} 
		return account;
	}
	
	/**
	 * 这个方法是为了保存中国电信下线时的信息
	 * @param account
	 * @return
	 */
	public boolean saveChinaNetLogoutParamStr(ChinaNetLogoutParamStr account) {
		ContentValues values = new ContentValues();
		values.put("ip", account.ip);
		values.put("realIp", account.realIp);
		values.put("paramStr", account.paramStr);
		ChinaNetLogoutParamStr temp = getChinaNetLogoutParamStr();
		if (null == temp) {
			return (mDb.insert("logoutParamStr", null, values)) > 0;
		} else {
			return (mDb.update("logoutParamStr", values, "_id=?", new String[] { ""
					+ temp.id })) > 0;
		}
	}
	
	/**
	 * 这个方法是获取代表中国电信下线时的信息
	 * @return ChinaNetLogoutParamStr
	 */
	public ChinaNetLogoutParamStr getChinaNetLogoutParamStr() {
		ChinaNetLogoutParamStr account = null;
		try{
			Cursor mCursor = mDb.query("logoutParamStr", null, null, null, null, null,null);
			if (mCursor.moveToFirst()) {
				account = new ChinaNetLogoutParamStr();
				account.id = mCursor.getInt(0);
				account.ip = mCursor.getString(1);
				account.realIp = mCursor.getString(2);
				account.paramStr = mCursor.getString(3);
			}
			mCursor.close();
		}catch(Exception e){
			e.printStackTrace();
		} 
		return account;
	}

	/**
	 * 这个方法是为了保存中国移动的帐号信息
	 * @param account
	 * @return
	 */
	public boolean saveAccount(Account account) {
		ContentValues values = new ContentValues();
		values.put("username", account.userName);
		values.put("password", account.password);
		values.put("autologin", account.autoLogin); 
		Account temp = getAccount();
		if (null == temp) {
			return (mDb.insert("account", null, values)) > 0;
		} else {
			return (mDb.update("account", values, "_id=?", new String[] { ""
					+ temp.id })) > 0;
		}
	}
	
	/**
	 * 这个方法是为了保存中国电信的帐号信息
	 * @param account
	 * @return
	 */
	public boolean saveChinaNetAccount(ChinaNetAccount account) {
		ContentValues values = new ContentValues();
		values.put("username", account.userName);
		values.put("password", account.password);
		values.put("address", account.address);
		values.put("autologin", account.autoLogin); 
		ChinaNetAccount temp = getChinaNetAccount();
		if (null == temp) {
			return (mDb.insert("chinaaccount", null, values)) > 0;
		} else {
			return (mDb.update("chinaaccount", values, "_id=?", new String[] { ""
					+ temp.id })) > 0;
		}
	}
	
	/**
	 * 这个方法是为了保存中国联通的帐号信息
	 * @param account
	 * @return
	 */
	public boolean saveUnicomAccount(ChinaUnicomAccount account) {
		ContentValues values = new ContentValues();
		values.put("username", account.userName);
		values.put("password", account.password);
		values.put("address", account.address);
		values.put("autologin", account.autoLogin); 
		ChinaUnicomAccount temp = getUnicomAccount();
		if (null == temp) {
			return (mDb.insert("unicomaccount", null, values)) > 0;
		} else {
			return (mDb.update("unicomaccount", values, "_id=?", new String[] { ""
					+ temp.id })) > 0;
		}
	}
	
	public WebAuth getWebAuth() {
		WebAuth webAuth = null;
		Cursor mCursor = mDb.query("webauth", null, null, null, null, null, null, null);
		if (mCursor.moveToFirst()) {
			webAuth = new WebAuth();
			webAuth.id = mCursor.getInt(0);
			webAuth.userName = mCursor.getString(1);
			webAuth.password = mCursor.getString(2);
			webAuth.wlanacip = mCursor.getString(3);
			webAuth.wlanacname = mCursor.getString(4);
			webAuth.wlanuserip = mCursor.getString(5);
//			webAuth.loginurl = mCursor.getString(6);
			webAuth.logonsessid = mCursor.getString(6);
			Log.e("webAuth", "" + webAuth.password);
			System.err.println(webAuth.id +"llllllllllllllllllllllllllllllllllllll");
//			webAuth.autoLogin = mCursor.getInt(3);
		}
		mCursor.close();
		return webAuth;
	}

	public boolean saveWebAuth(WebAuth webauth) {
		try {
			ContentValues values = new ContentValues();
			values.put("username", webauth.userName);
			values.put("password", webauth.password);
			values.put("wlanacip", webauth.wlanacip);
			values.put("wlanacname", webauth.wlanacname);
			values.put("wlanuserip", webauth.wlanuserip);
			values.put("logonsessid", webauth.logonsessid);
//			values.put("loginurl",  webauth.loginurl);
			WebAuth temp = getWebAuth();
			if (null == temp) {
				return (mDb.insert("webauth", null, values)) > 0;
			} else {
				return (mDb.update("webauth", values, "_id=?", new String[] { ""
						+ temp.id })) > 0;
			}
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
		
	}
	
	public AppVersionInfo getVersionInfo() {
		AppVersionInfo versionInfo = null;
		Cursor mCursor = mDb.query("version", null, null, null, null, null, null, null);
		if (mCursor.moveToFirst()) {
			versionInfo = new AppVersionInfo();
			versionInfo.id = mCursor.getInt(0);
			versionInfo.version = mCursor.getString(1); 
			versionInfo.downloadurl = mCursor.getString(2); 
			versionInfo.description = mCursor.getString(3);   
//			webAuth.autoLogin = mCursor.getInt(3);
		}
		mCursor.close();
		return versionInfo;
	}

	public boolean saveVersionInfo(AppVersionInfo versionInfo) {
		try {
			ContentValues values = new ContentValues();
			values.put("version", versionInfo.version);
			values.put("downloadurl", versionInfo.downloadurl);
			values.put("description", versionInfo.description); 
			AppVersionInfo temp = getVersionInfo();
			if (null == temp) {
				return (mDb.insert("version", null, values)) > 0;
			} else {
				return (mDb.update("version", values, "_id=?", new String[] { ""
						+ temp.id })) > 0;
			}
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}
	
	public Address getAddress() {
		Address address = null;
		Cursor mCursor = mDb.query("address", null, null, null, null, null, null, null);
		if (mCursor.moveToFirst()) {
			address = new Address();
			address.id = mCursor.getInt(0);
			address.city = mCursor.getString(1); 
			address.town = mCursor.getString(2); 
		}
		mCursor.close();
		return address;
	}

	public boolean saveAddress(Address address) {
		try {
			ContentValues values = new ContentValues();
			values.put("version", address.city);
			values.put("downloadurl", address.town); 
			Address temp = getAddress();
			if (null == temp) {
				return (mDb.insert("address", null, values)) > 0;
			} else {
				return (mDb.update("address", values, "_id=?", new String[] { ""
						+ temp.id })) > 0;
			}
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}
}
